package com.ruoyi.culture.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.annotation.InnerAuth;
import com.ruoyi.culture.domain.RegisterInfo;
import com.ruoyi.culture.domain.RegisterPart;
import com.ruoyi.culture.mapper.RegisterInfoMapper;
import com.ruoyi.culture.service.feign.SysProfileService;
import com.ruoyi.culture.service.feign.SysUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import feign.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;


@Service
public class RegisterInfoService {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Autowired
    RegisterInfoMapper registerInfoMapper;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    SysProfileService sysProfileService;

    @Transactional(rollbackFor = RuntimeException.class)
    public void insert(RegisterPart registerPart) {
        int i = registerInfoMapper.addOne(registerPart);
        if (i==0){
            throw new RuntimeException("注册信息添加失败");
        }
    }


    public RegisterInfo searchOne(String username) {
        SysUser user = sysUserService.getId(username);
        RegisterPart register = registerInfoMapper.search(username);
        RegisterInfo registerInfo=new RegisterInfo();
        try {
            BeanUtils.copyProperties(user,registerInfo);
            BeanUtils.copyProperties(register,registerInfo);
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
        return registerInfo;
    }

    public void update(RegisterPart registerPart) {
        registerPart.setModifiedTime(new Date());
        SysUser sysUser =new SysUser();
        BeanUtils.copyProperties(registerPart,sysUser);
        SysUser user = sysUserService.getId(registerPart.getUserName());
        sysUser.setUserId(user.getUserId());
        AjaxResult ajaxResult = sysProfileService.updateProfile(sysUser);
        if (!ajaxResult.isSuccess()){
            throw new RuntimeException("修改用户信息失败");
        }
        int updateResult = registerInfoMapper.update(registerPart);
        if (updateResult==0){
            throw new RuntimeException("修改用户信息失败");
        }
    }
}
